package com.sairui.xiaoruilib;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.net.http.SslError;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.sairui.xiaoruilib.bean.SearchBean;
import com.sairui.xiaoruilib.manager.PopupWindowHelper;
import com.sairui.xiaoruilib.util.GsonConvert;
import com.sairui.xiaoruilib.util.NetworkUtil;
import com.sairui.xiaoruilib.widgets.NewVoiceView;
import com.sairui.xiaoruilib.widgets.WXBottomTouchView;
import com.sairui.xiroruilib.recognize.VoiceRecognizeManager;
import com.sairui.xiroruilib.speak.SpeakManager;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Random;

/**
 * Created by sunqiyong on 2018/6/30.
 */

public class XiaoRuiFragment extends Fragment implements View.OnClickListener {
    private View mRootView;
    
    private WebView mWebView;
    private View mMengCeng;
    private View mBottomView;
    private RelativeLayout mNoData;
    private ProgressBar mProgressBar;

    private SearchBean mSearchBean;//与h5交互实体类

    private MediaPlayer mMediaStartPlayer;//开始语音识别播放声音
    private MediaPlayer mMediaEndPlayer;//结束语音识别播放声音

    //是否加载H5发生错误
    private boolean isNetError = false;
    //用于处理第一次加载完成，因为不知原因，网页progress 为 100 会执行2次
    private boolean isFirstLoadWeb = true;

    private PopupWindowHelper popupWindowHelper;
    private View voicePopView;
    private TextView mVoiceContent;
    private TextView mVoiceContentHint;
    private NewVoiceView mVoiceView;
    private TextView mVoiceHintContent;
    private ImageView mPopRobotIcon;
    private AnimationDrawable animationDrawable;
    private LinearLayout mLLNoVoiceData;
    private LinearLayout mLLSpeakTimeLess;

    private long mSpeakTime = 0;//说话的时间
    private String mBaiDuSpeakContent = "";
    private Boolean isPointCancel = true;//是否手指取消

    public static XiaoRuiFragment getInstance(){
        return new XiaoRuiFragment();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mRootView == null) {
            mRootView = inflater.inflate(R.layout.fragment_xiao_rui, null);
            initViews();
        }
        ViewGroup parent = (ViewGroup) mRootView.getParent();
        if (parent != null) {
            parent.removeView(mRootView);
        }
        return mRootView;
    }

    private void initViews() {
        mWebView = mRootView.findViewById(R.id.web_view);
        mMengCeng = mRootView.findViewById(R.id.men_ceng);
        mBottomView = mRootView.findViewById(R.id.bottom_line);
        mNoData = mRootView.findViewById(R.id.rl_no_data);
        mProgressBar = mRootView.findViewById(R.id.pb_progressbar);

        mMengCeng.setOnClickListener(this);

        //初始化 开始语音识别播放声音 和 结束语音识别播放声音
        mMediaStartPlayer = MediaPlayer.create(getActivity(), R.raw.start);
        mMediaEndPlayer = MediaPlayer.create(getActivity(), R.raw.end);

        mSearchBean = new SearchBean();
        initWebView();
        mWebView.loadUrl("https://192.168.1.65:50000/fine-robot/xiaorui/index");

        //底部语音弹窗
        voicePopView = LayoutInflater.from(getActivity()).inflate(R.layout.pop_new_main_voice, null);
        mVoiceContent = voicePopView.findViewById(R.id.voice_content);
        mVoiceContentHint = voicePopView.findViewById(R.id.voice_content_hint);
        mVoiceView = voicePopView.findViewById(R.id.voice_view);
        mVoiceHintContent = voicePopView.findViewById(R.id.voice_hint);
        mPopRobotIcon = voicePopView.findViewById(R.id.robot_icon);
        mLLNoVoiceData = voicePopView.findViewById(R.id.no_voice_data);
        mLLSpeakTimeLess = voicePopView.findViewById(R.id.speak_time_less);
        animationDrawable = (AnimationDrawable) mPopRobotIcon.getBackground();
        if (animationDrawable != null && !animationDrawable.isRunning()) {
            animationDrawable.start();
        }
        popupWindowHelper = new PopupWindowHelper(voicePopView);
    }

    @Override
    public void onResume() {
        super.onResume();
        VoiceRecognizeManager.getInstance().setRecognizeListener(new VoiceRecognizeManager.VoiceRecognizeListener() {
            @Override
            public void onStart() {
                mMediaStartPlayer.start();
            }

            @Override
            public void onEnd() {
                if (TextUtils.isEmpty(mBaiDuSpeakContent)) {
                    VoiceRecognizeManager.getInstance().cancelRecognize();
                    //如果不是手指上滑动引起的取消
                    if (!isPointCancel) {
                        mLLSpeakTimeLess.setVisibility(View.INVISIBLE);
                        mLLNoVoiceData.setVisibility(View.VISIBLE);
                        mVoiceView.emptyVoice();
                    }
                }
            }

            @Override
            public void onPartialResult(String result) {
                mVoiceContentHint.setVisibility(View.INVISIBLE);
                mBaiDuSpeakContent = result;
                setDataToWidget(mVoiceContent, result);
            }

            @Override
            public void onFinalResult(String result) {
                setDataToWidget(mVoiceContent, result);
                popupWindowHelper.dismiss();
                VoiceRecognizeManager.getInstance().cancelRecognize();
                mVoiceView.emptyVoice();
                mMengCeng.setVisibility(View.GONE);
                mSearchBean.setQueryContent(result);
                String msg = GsonConvert.toJson(mSearchBean);
                mWebView.loadUrl("javascript:createConversation('" + msg + "')");
            }

            @Override
            public void onVolume(int volumePercent, int volume) {
                if (volumePercent != 0) {
                    volumePercent = volumePercent / 2;
                    mVoiceView.setVoiceLevel(volumePercent);//音量大小
                    Random random = new Random();
                    mVoiceView.setVoiceLevel(random.nextInt(20));//音量大小
                    mVoiceView.setVoiceLevel(random.nextInt(20));//音量大小
                }
            }

        });
    }

    public void start_recognize() {
        if(getActivity() == null){
            return;
        }
        if(!NetworkUtil.isConnected(getActivity())){
            showShortToast("网络不给力，请检查网络设置");
            return;
        }
        mLLSpeakTimeLess.setVisibility(View.INVISIBLE);
        mLLNoVoiceData.setVisibility(View.INVISIBLE);
        SpeakManager.getInstance().stop();

        startTextListener();

        isPointCancel = false;
        mSpeakTime = System.currentTimeMillis();
        mBaiDuSpeakContent = "";
        startRecognize();

        mVoiceContent.setTextColor(ContextCompat.getColor(getActivity(),R.color.main_voice_pop_black));
        mVoiceHintContent.setTextColor(ContextCompat.getColor(getActivity(),R.color.main_voice_pop_grey));
        setDataToWidget(mVoiceContent, "");
        setDataToWidget(mVoiceHintContent, "手指上滑 取消发送");
        mVoiceView.setCancel(false);
        mMengCeng.setVisibility(View.VISIBLE);
        popupWindowHelper.showAsPopUp(mBottomView);
    }

    public void cancel_recognize() {
        if(getActivity() == null || !NetworkUtil.isConnected(getActivity())){
            return;
        }

        isPointCancel = true;
        VoiceRecognizeManager.getInstance().stopRecognize();
        VoiceRecognizeManager.getInstance().cancelRecognize();
        mVoiceContent.setTextColor(ContextCompat.getColor(getActivity(),R.color.main_voice_pop_grey));
        mVoiceHintContent.setTextColor(ContextCompat.getColor(getActivity(),R.color.main_voice_pop_black));
        setDataToWidget(mVoiceHintContent, "手指松开 取消发送");
        mVoiceView.setCancel(true);
        mBaiDuSpeakContent = "";
    }

    public void actionUp() {
        if(getActivity() == null || !NetworkUtil.isConnected(getActivity())){
            return;
        }
        VoiceRecognizeManager.getInstance().stopRecognize();
        isInTextListener = false;
        mVoiceContentHint.setVisibility(View.INVISIBLE);
        if ((System.currentTimeMillis() - mSpeakTime) < 700) {
            VoiceRecognizeManager.getInstance().cancelRecognize();
            mLLSpeakTimeLess.setVisibility(View.VISIBLE);
            mLLNoVoiceData.setVisibility(View.INVISIBLE);
        }
        mSpeakTime = 0;
        mMediaEndPlayer.start();
        //如果是手指上滑引起的取消
        if (isPointCancel) {
            popupWindowHelper.dismiss();
            mMengCeng.setVisibility(View.GONE);
            mVoiceView.emptyVoice();
        }
    }

    private void initWebView() {
        WebSettings webSetting = mWebView.getSettings();
        webSetting.setDefaultTextEncodingName("UTF-8");
        webSetting.setBuiltInZoomControls(false);// 显示缩放按钮(wap网页不支持)
        webSetting.setUseWideViewPort(false);// 支持双击缩放(wap网页不支持)
        //能够执行JavaScript脚本
        webSetting.setJavaScriptEnabled(true);
        MainJsForAndorid mMainJsForAndorid = new MainJsForAndorid(new WeakReference<Activity>(getActivity()));
        mWebView.addJavascriptInterface(mMainJsForAndorid, "android");
        mMainJsForAndorid.setJsListener(new MainJsForAndorid.JsListener() {
            @Override
            public void hideKeyboard() {
            }

            @Override
            public void webSpeak(String speak) {
                speak(speak);
            }
        });
        //支持在当前WebView窗口加载网页
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView webView, String s) {
                super.onPageFinished(webView, s);
            }

            @Override
            public void onReceivedError(WebView webView, int i, String s, String s1) {
                super.onReceivedError(webView, i, s, s1);
                Log.e("onReceivedError",s + "  " + s1 + "   " + i);
                if ((i == -1 || i == -8) && "net::net::<unknown>".equals(s)) {
                    isNetError = true;
                    ViewGroup.LayoutParams params = mNoData.getLayoutParams();
                    params.height = mWebView.getHeight();
                    mNoData.setLayoutParams(params);
                    mNoData.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                Log.e("onReceivedError","asdgfadsgfad   " );
                handler.proceed();
            }
        });
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                //进度发生变化,可以获取到进度
                if (null != mProgressBar) {
                    mProgressBar.setProgress(newProgress);
                    if (newProgress == 100 && isFirstLoadWeb) {
                        isFirstLoadWeb = false;
                        if (!isNetError) {
                            mNoData.setVisibility(View.GONE);
                        }
                        mProgressBar.setVisibility(View.GONE);
                        String msg = GsonConvert.toJson(mSearchBean);
                        mWebView.loadUrl("javascript:queryConversationHistory('" + msg + "')");
                    }
                }
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
            }

        });
    }

    /**
     * android 6.0 以上需要动态申请权限
     */
    private void speak(String content) {
        String permissions[] = {
                Manifest.permission.INTERNET,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.MODIFY_AUDIO_SETTINGS,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.ACCESS_WIFI_STATE,
                Manifest.permission.CHANGE_WIFI_STATE
        };

        ArrayList<String> toApplyList = new ArrayList<String>();

        for (String perm : permissions) {
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(getActivity(), perm)) {
                toApplyList.add(perm);
                //进入到这里代表没有权限.
            }
        }
        String tmpList[] = new String[toApplyList.size()];
        if (!toApplyList.isEmpty()) {
            ActivityCompat.requestPermissions(getActivity(), toApplyList.toArray(tmpList), 123);
        }else {
            SpeakManager.getInstance().speak(content);
        }
    }

    protected void showShortToast(String pMsg) {
        if(pMsg == null || "".equals(pMsg) || "null".equals(pMsg)){
            return;
        }
        if(pMsg.startsWith("Unable to resolve host")){
            return;
        }
        if(pMsg.startsWith("Failed to connect")){
            pMsg = "网络不给力，请检查网络设置";
        }
        
        Toast.makeText(getActivity(),pMsg,Toast.LENGTH_SHORT).show();
    }

    private Boolean isInTextListener = true;
    private int mTextListenerPosition = 1;
    public void startTextListener(){
        isInTextListener = true;
        mTextListenerPosition = 1;
        mVoiceContentHint.setVisibility(View.VISIBLE);
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (isInTextListener){
                    try {
                        Thread.sleep(400);
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                String text = "我正在听";
                                for(int i = 0; i<= mTextListenerPosition % 3 ; i++){
                                    text = String.valueOf(text + ".");
                                }
                                mTextListenerPosition ++;
                                mVoiceContentHint.setText(text);
                            }
                        });
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    /**
     * android 6.0 以上需要动态申请权限
     */
    private void startRecognize() {
        String permissions[] = {Manifest.permission.RECORD_AUDIO,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.INTERNET,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        };

        ArrayList<String> toApplyList = new ArrayList<String>();

        for (String perm :permissions){
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(getActivity(), perm)) {
                toApplyList.add(perm);
                //进入到这里代表没有权限.
            }
        }
        String tmpList[] = new String[toApplyList.size()];
        if (!toApplyList.isEmpty()){
            ActivityCompat.requestPermissions(getActivity(), toApplyList.toArray(tmpList), 923);
        }else{
            VoiceRecognizeManager.getInstance().startRecognize();
        }

    }

    protected void setDataToWidget(TextView view,String s){
        if(s != null){
            view.setText(s);
        }
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.men_ceng) {//去除底部语音输入弹框
            dismissPop();
        }
    }

    public void dismissPop(){
        if(popupWindowHelper == null || mMengCeng == null || mVoiceView == null){
            return;
        }
        popupWindowHelper.dismiss();
        mMengCeng.setVisibility(View.GONE);
        mVoiceView.emptyVoice();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
